package com.example.service.impl;

import com.example.mapper.ClazzMapper;
import com.example.pojo.*;
import com.example.mapper.EmpMapper;
import com.example.mapper.ExprMapper;
import com.example.service.EmpService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private ExprMapper exprMapper;

    @Autowired
    private ClazzMapper clazzMapper;


    /**
     * 分页查询员工数据
     */
    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
        //设置分页参数(PageHelper)
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());

        //执行查询、解析结果, 并封装
        Page<Emp> p = (Page<Emp>) empMapper.list(empQueryParam);

        return new PageResult<>(p.getTotal(), p.getResult());
    }

    /**
     * 新增员工
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Emp emp) {
        //1.保存员工的基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.insert(emp);

        //2.保存员工的工作经历
        List<EmpExpr> empExprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(empExprList)) {
            empExprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            exprMapper.insertBatch(empExprList);
        }
    }

    /**
     * 批量删除员工
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Integer> ids) throws Exception {
        //1.检查是否有班级还与员工有关联
        List<Clazz> clazzList = clazzMapper.getByEmpIds(ids);
        if (!clazzList.isEmpty()) {
            throw new Exception("所选员工中有班级的班主任职位，不能删除");
        }

        //2.删除员工基本信息
        empMapper.deleteByIds(ids);

        //3.删除员工的工作经历
        exprMapper.deleteByEmpIds(ids);
    }

    /**
     * 根据ID查询员工基本信息
     */
    @Override
    public Emp getInfo(Integer id) {
        return empMapper.getById(id);
    }

    /**
     * 修改员工信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Emp emp) {
        //1.修改员工基本信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);

        //2.先删除员工的工作经历,再进行添加
        Integer empId = emp.getId();
        exprMapper.deleteByEmpIds(Arrays.asList(empId));
        List<EmpExpr> empExprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(empExprList)) {
            empExprList.forEach(empExpr -> empExpr.setEmpId(empId));
            exprMapper.insertBatch(empExprList);
        }
    }

    /**
     * 员工登录
     */
    @Override
    public LoginInfo login(Emp emp) {
        //调用mapper接口,根据用户名和密码查询员工信息
        Emp result = empMapper.getByUsernameAndPassword(emp.getUsername(), emp.getPassword());

        //判断员工信息是否为空
        if (result != null) {
            log.info("员工登录成功, 员工信息为{}", result);

            return LoginInfo.builder()
                    .id(result.getId())
                    .username(result.getUsername())
                    .name(result.getName())
                    .token(result.getId().toString()).build();
        }

        //员工不存在, 返回null
        return null;
    }

    /**
     * 查询所有员工
     */
    @Override
    public List<Emp> list() {
        return empMapper.getAllInfo();
    }

    /**
     * 根据用户名和密码修改密码
     */
    @Override
    public void updatePassword(PasswordParam passwordParam) {
        //调用mapper接口,根据用户名和密码查询员工信息
        Emp result = empMapper.getByUsernameAndPassword(passwordParam.getUsername(), passwordParam.getOldPassword());

        if (result != null) {
            //员工存在, 修改密码
            empMapper.updateByUsernameAndPassword(passwordParam);
        } else {
            //员工不存在, 抛出异常
            throw new RuntimeException("用户名或密码错误");
        }
    }
}
